package com.ruoyi.framework.security.sso;

import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.MessageUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.SysPasswordService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.List;

/**
 * sso登录实现
 */
public class SsoAuthenticationProvider implements AuthenticationProvider {
    private static final Logger log = LoggerFactory.getLogger(SsoAuthenticationProvider.class);
    @Autowired
    private ISysUserService userService;
    @Autowired
    private ISysDeptService deptService;
    @Autowired
    private SysPermissionService permissionService;

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if (authentication.isAuthenticated()) {
            return authentication;
        }
        //获取过滤器封装的token信息
        SsoAuthenticationToken authenticationToken = (SsoAuthenticationToken) authentication;
        String code = (String) authenticationToken.getPrincipal();
        // TODO: 2023/10/27 此处应根据sso的code码取获取用户信息
        String username = "admin";
        SysUser user = userService.selectUserByUserName("admin");
        if (StringUtils.isNull(user)) {
            log.info("登录用户：{} 不存在.", username);
            throw new ServiceException(MessageUtils.message("user.not.exists"));
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", username);
            throw new ServiceException(MessageUtils.message("user.password.delete"));
        } else if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            log.info("登录用户：{} 已被停用.", username);
            throw new ServiceException(MessageUtils.message("user.blocked"));
        }
        LoginUser loginUser = this.createLoginUser(user);
        SsoAuthenticationToken authenticationResult = new SsoAuthenticationToken(loginUser);
        return authenticationResult;
    }

    public LoginUser createLoginUser(SysUser user) {
        SysDept mDept = this.masterDept(user);

        return new LoginUser(user.getUserId(), mDept, user, permissionService.getMenuPermission(user));
    }

    private SysDept masterDept(SysUser user) {
        List<SysDept> lists = deptService.queryUserDepts(user.getUserId());
        SysDept sysDept = null;
        for (SysDept item : lists) {
            if (item.getEmplRcd().equals("0")) {
                sysDept = item;
                break;
            }
        }
        if (sysDept == null && lists.size() > 0) {
            sysDept = lists.get(0);
        }
        return sysDept;
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return SsoAuthenticationToken.class.isAssignableFrom(authentication);
    }
}
